package com.mrdeer.merchant.common.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mrdeer.common.util.EncryptUtil;
import com.mrdeer.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：xie jianchu
 * @date ：Created in 2020/9/11 0011 11:55
 */
@Slf4j
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //0.放行静态资源
        String requestURL = httpServletRequest.getRequestURL().toString();
        log.info("requestURL:{}", requestURL);
        String[] urls = {".js", ".css", ".ico", ".jpg", ".png", ".gif"};       //不需要过滤的资源
        if (StringUtil.isContains(urls, requestURL)
                || requestURL.indexOf("/v2/api-docs") != -1
                || requestURL.indexOf("/swagger-resources") != -1
                || requestURL.indexOf("/swagger-ui.html") != -1
                || requestURL.indexOf("/merchants/register") != -1
                || requestURL.indexOf("/sms") != -1
                || requestURL.indexOf("/my/tenants-merchants") != -1
                || requestURL.indexOf("/doc.html") != -1) {
            log.info("#############该资源放行#############" + requestURL);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //1.校验jsonToken
        String jsonToken = httpServletRequest.getHeader("jsonToken");
        log.info("jsonToken:{}", jsonToken);
        if (StringUtils.isBlank(jsonToken)) {
            responseMessage(999911, "调用微服务-没有jsonToken令牌", httpServletRequest, httpServletResponse);
            return;
        }
        //2.base64解码之后有没有当前租户的权限信息
        String json = EncryptUtil.decodeUTF8StringBase64(jsonToken);
        log.info("json令牌:{}", json);
        Map tokenMap = JSON.parseObject(json, Map.class);
        log.info("tokenMap:{}", JSON.toJSONString(tokenMap));

        String payload = (String) tokenMap.get("payload");     //需要注意payload的值是字符串需要再次转map
        log.info("payload:{}", payload);
        Map payloadMap = JSON.parseObject(payload, Map.class);
        log.info("payloadMap:{}", JSON.toJSONString(payloadMap));

        //增加将当前登入用户信息放入requestAttribute

    }

    /**
     * 由于全局异常处理器无法捕获 filter中的异常信息 利用此map将异常信息直接响应到前端
     *
     * @param code                响应码
     * @param desc                响应信息
     * @param httpServletRequest  请求
     * @param httpServletResponse 回应
     * @throws IOException
     */
    public void responseMessage(int code, String desc, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        Map<String, Object> exceptionMap = new HashMap<String, Object>();
        exceptionMap.put("code", code);
        exceptionMap.put("desc", desc);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().print(JSONObject.toJSON(exceptionMap));
    }
}
